//
//  CZHomeViewController.swift
//  微博
//
//  Created by 范承志 on 16/6/11.
//  Copyright © 2016年 fanchengzhi. All rights reserved.
//

import UIKit

//cell可重用标识
private let cellID = "cellID"

class CZHomeViewController: CZVisitorViewController {
    
    //保存微博数据数组
    let statusListViewModel = CZStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //判断用户是否登录
        if !isLogin {
            
            //设置访客视图信息
            visitorView?.setupVisitorViewInfo(imgName: nil, tilte: nil)
            return
        }
        setupUI()
        getStatusData()
    }
    
    // MARK: - 监听事件
    @objc private func leftClick(){
        print("左侧按钮点击")
    }
    
    @objc private func rightClick(){
        // 创建临时控制器
        let tempVc = CZTempViewController()
        // 隐藏 tabbar
        tempVc.hidesBottomBarWhenPushed = true
        // 跳转控制器
        navigationController?.pushViewController(tempVc, animated: true)
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        setupNav()
        setupTableViewInfo()
        
        //添加tipLabel
        if let nav = self.navigationController  {
            
            //表示导航控制器存在
            nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
            
            //获取最大Y轴
            tipLabel.frame = CGRect(x: 0, y: nav.navigationBar.frame.maxY - 35, width: nav.navigationBar.frame.width, height: 35)
            
        }
    }
    
    // MARK: - 设置TableView相关的信息
    private func setupTableViewInfo(){
        
        //设置数据源
        tableView.dataSource = self
        tableView.delegate = self
        
        //注册cell
        tableView.register(CZStatusCell.self, forCellReuseIdentifier: cellID)
        
        //设置cell的行高
        //自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        
        //预估行高
        tableView.estimatedRowHeight = 200
        
        //TableView显示样式
        tableView.separatorStyle = .none
        
        //设置footView
        tableView.tableFooterView = bottomView
        
        //添加自定义下拉刷新控件
        tableView.addSubview(refreshControl)
        
        refreshControl.addTarget(self, action: #selector(getStatusData), for: UIControlEvents.valueChanged)
    }
    // MARK: - 设置导航
    private func setupNav(){
        
        // 快速创建带有Title和图片的button按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(highlightedImgName: "navigationbar_pop", target: self, action: #selector(leftClick))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(highlightedImgName: "navigationbar_friendsearch", target: self, action: #selector(rightClick))
    }
    
    //tipLabel动画
    fileprivate func startTipAnimation(message: String) {
        
        if tipLabel.isHidden == false {
            
            //表示正在执行动画
            return
        }
        
        tipLabel.isHidden = false
        
        tipLabel.text = message
        
    
        UIView.animate(withDuration: 1, animations: {

            self.tipLabel.transform = CGAffineTransform(translationX: 0, y: self.tipLabel.frame.height)
            
        }) { (_) in
            
            UIView.animate(withDuration: 1, animations: {
                
                self.tipLabel.transform = CGAffineTransform.identity
                }, completion: { (_) in
                    
                    self.tipLabel.isHidden = true
            })
        }
    }
    
    //懒加载控件
    //菊花
    fileprivate lazy var bottomView: UIActivityIndicatorView = {
        
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        
        //设置颜色
        view.color = UIColor.purple
        return view
    }()
    
    //自定义下拉刷新控件
    fileprivate lazy var refreshControl: CZRefreshControl = CZRefreshControl()
    
    //tipLabel
    fileprivate lazy var tipLabel: UILabel = {
        
        let label = UILabel(textColor: UIColor.white, fontSize: CZNormalFontSize, text: "没有加载到最新微博数据")
        
        label.backgroundColor = UIColor.orange
        
        label.textAlignment = .center
        
        //默认状态隐藏
        label.isHidden = true
        
        return label
    }()
    
}

//请求数据
extension CZHomeViewController{
    
    func getStatusData(){
        
        // 委托 statusListViewModel 请求数据
        statusListViewModel.getHomeData(isPullUp:bottomView.isAnimating) { (isSuccess, message) in
            
            //不是上拉加载 执行tip动画
            if !self.bottomView.isAnimating {
                
                self.startTipAnimation(message: message)
            }
            
            
            if !isSuccess {
                
                print("请求数据失败")
                
            } else {
                
                // 刷新 UI
                self.tableView.reloadData()
            }
            
            self.endRefreshing()
            
        }
    }
    
    //停止下拉和上拉动画
    func endRefreshing(){
        
        //停止动画
        self.bottomView.stopAnimating()
        
        //下拉刷新也要停止
        self.refreshControl.endRefreshing()
    }
}

//数据源方法
extension CZHomeViewController: UITableViewDataSource,UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusListViewModel.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as!CZStatusCell
        
        //给cell赋值
        cell.statusViewModel = statusListViewModel.dataArray[indexPath.row]
        
        //取消cell选中效果
        cell.selectionStyle = .none
        
        return cell
    }
    
    //将要显示的cell
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        // 如果 indexPath.row == 19  -> count - 1 代表显示最后一个 cell
        if indexPath.row == statusListViewModel.dataArray.count - 1 && !bottomView.isAnimating {
           
            // 开启动画
            bottomView.startAnimating()
            
            // 马上请求数据
            getStatusData()
        }
    }
}



